package com.xuqm.sdhbwfu.app.ui

import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.alertview.AlertView
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions
import com.xuqm.base.App
import com.xuqm.base.adapter.CommonAdapter
import com.xuqm.base.adapter.ViewHolder
import com.xuqm.base.common.*
import com.xuqm.base.dialog.loading.LoadingDialog
import com.xuqm.base.extensions.log
import com.xuqm.base.extensions.runWithPermission
import com.xuqm.base.extensions.showMessage
import com.xuqm.base.ui.BaseActivity
import com.xuqm.sdhbwfu.app.R
import com.xuqm.sdhbwfu.app.databinding.ActivityProcessingDetailBinding
import com.xuqm.sdhbwfu.app.model.JobListModel
import com.xuqm.sdhbwfu.app.viewmodel.ProcessingDetailViewModel
import com.xuqm.sdhbwfu.core.extensions.addItemDecorationForVertical
import java.io.File

class ProcessingDetailActivity : BaseActivity<ActivityProcessingDetailBinding>() {
    override fun getLayoutId(): Int = R.layout.activity_processing_detail
    override fun fullscreen(): Boolean = true

    private var str = ""
    private var mId: Int = -1

    lateinit var model: JobListModel

    private val mData = mutableListOf<JobListModel.ItemValue>()

    private val vm: ProcessingDetailViewModel by viewModels()

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        binding.detailListRv.layoutManager = LinearLayoutManager(mContext)
        binding.detailListRv.addItemDecorationForVertical(10)
        binding.detailListRv.adapter = adapter
    }

    override fun lateInitView() {
        super.lateInitView()
        binding.inspectionBackLyt.setOnClickListener { finish() }

        binding.detailBtnSkip.setOnClickListener {
            startActivityForResult(
                Intent(
                    mContext,
                    ProcessingSkipActivity::class.java
                ).apply {
                    putExtra("mId", mId)
                    putExtra("item", GsonImplHelp.get().toJson(model))
                }, 10086
            )
        }
        binding.detailBtnFinish.setOnClickListener {

            if (model.upload && model.attachment.isNullOrEmpty()) {
                "必须上传附件".showMessage()
                return@setOnClickListener
            }

            val ll = model.itemValue.filter { it.value.isNullOrEmpty() }

            if (!ll.isNullOrEmpty()) {
                "数据填写不完整".showMessage()
                return@setOnClickListener
            }
            LoadingDialog.showDialog("")
            model.status = "finished"
            vm.inspectionUpdate(mId,model)
        }
    }

    override fun onResume() {
        super.onResume()
//        if (needCheck) openAlert()
    }

    private var needCheck = true
    private fun openAlert() {
        needCheck = false
        AlertView(
            "扫描设备",
            model.concreteName,
            "",
            arrayOf("取消", "扫描"),
            null,
            AppManager.getInstance().activity,
            AlertView.Style.Alert
        ) { _, pos ->
            when (pos) {
                0 -> finish()
                else -> {
                    App.getInstance().runOnUiThread {
                        runWithPermission(
                            Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
                            rationaleMethod = {
                                "需要开启摄像头权限才能进行扫码验证操作".showMessage()
                                finish()
                            },
                            permanentDeniedMethod = {
                                "需要开启摄像头权限才能进行扫码验证操作,请在手机权限管理页面打开相关权限。".showMessage()
                                finish()
                            },
                            callback = {
                                ScanUtil.startScan(
                                    this, 1111, HmsScanAnalyzerOptions.Creator().setHmsScanTypes(
                                        HmsScan.QRCODE_SCAN_TYPE
                                    ).create()
                                );
                            })
                    }
                }
            }
        }.show()
    }

    override fun initData() {
        super.initData()
        mId = intent.getIntExtra("mId", -1)
        str = intent?.getStringExtra("item") ?: ""
        str.log()

        vm.status.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                model.attachment.add(it.id)
                adapter.notifyDataSetChanged()
            }
        }
        vm.up.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                setResult(
                    RESULT_OK,
                    Intent().apply { putExtra("item", GsonImplHelp.get().toJson(it)) })
                finish()
            }
        }

        model = GsonImplHelp.get().toObject(str, JobListModel::class.java)

        model.concreteName?.also {
            binding.detailTitle.text = "当前巡检任务：$it"
        }

        mData.addAll(model.itemValue ?: emptyList())
        mData.sortByDescending { item -> item.sort }
        if (model.upload) {
            mData.add(JobListModel.ItemValue(-2001, "", null, 9999, "", "", "", "pic"))
        }
        adapter.notifyDataSetChanged()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1111) {
            if (resultCode == RESULT_OK) {
                val obj: HmsScan? = data?.getParcelableExtra(ScanUtil.RESULT)
                if (obj != null) {
                    if (model.rfid == obj.originalValue) {
                        "验证成功".showMessage()
                        needCheck = false
                    } else {
                        "验证失败".showMessage()
                        needCheck = true
                        openAlert()
                    }
                } else {
                    "扫码失败".showMessage()
                    needCheck = true
                    openAlert()
                }
            } else {
                needCheck = true
                openAlert()
            }

        } else if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                LoadingDialog.showDialog("")
                vm.picUpload(File(photoPath))
            }

        } else if (requestCode == 10086) {
            if (resultCode == RESULT_OK) {
                setResult(
                    RESULT_OK,
                    Intent().apply { putExtra("item", data?.getStringExtra("item")) })
                finish()
            }

        }
    }


    private val adapter =
        object : CommonAdapter<JobListModel.ItemValue>(R.layout.item_detail, mData) {
            override fun convert(holder: ViewHolder, item: JobListModel.ItemValue, position: Int) {
                holder.setText(R.id.item_detail_name, if (item.id == -2001) "上传附件" else item.name)
                holder.setBackgroundColor(R.id.item_app, Color.parseColor("#DBE3E6"))

                when (item.valueType) {
                    "number" -> {
                        holder.invisible(R.id.item_job_name)
                        holder.visible(R.id.item_detail_value)
                    }
                    "pic" -> {
                        if (model.attachment.isNullOrEmpty())
                            holder.setText(R.id.item_job_name, "选择附件")
                        else
                            holder.setText(R.id.item_job_name, "已上传")
                        holder.visible(R.id.item_job_name)
                        holder.invisible(R.id.item_detail_value)
                    }
                    else -> {
                        holder.setText(R.id.item_job_name, "选择结果")
                        holder.visible(R.id.item_job_name)
                        holder.invisible(R.id.item_detail_value)
                    }
                }

                holder.setText(R.id.item_detail_value, item.value)
                holder.setClickListener(R.id.item_job_name) {
                    if (item.valueType == "pic") {
                        if (model.attachment.isNullOrEmpty())

                            runWithPermission(
                                Manifest.permission.CAMERA,
                                rationaleMethod = {
                                    AlertView(
                                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用。",
                                        null, arrayOf("确定"), null, mContext,
                                        AlertView.Style.Alert
                                    ) { _, _ ->
                                    }.show()
                                },
                                permanentDeniedMethod = {
                                    "请在设置界面打开摄像头权限".showMessage()
                                    AlertView(
                                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用，请在应用权限管理页面打开相关权限。",
                                        null, arrayOf("确定"), null, mContext,
                                        AlertView.Style.Alert
                                    ) { _, _ ->
                                    }.show()
                                },
                                callback = {
                                    dispatchTakePictureIntent()
                                })
                    } else {
                        AlertView(
                            "选择结果",
                            "",
                            "取消",
                            arrayOf("正常", "异常"),
                            null,
                            AppManager.getInstance().activity,
                            AlertView.Style.ActionSheet
                        ) { _, pos ->
                            item.value = when (pos) {
                                0 -> "正常"
                                1 -> "异常"
                                else -> ""
                            }
                            holder.setText(
                                R.id.item_job_name, item.value ?: "选择结果"
                            )
                        }.show()
                    }

                }

                holder.getView<EditText>(R.id.item_detail_value).addTextChangedListener(object :
                    TextWatcher {
                    override fun beforeTextChanged(
                        s: CharSequence?,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {
                    }

                    override fun onTextChanged(
                        s: CharSequence?,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                    }

                    override fun afterTextChanged(s: Editable?) {
                        item.value = s.toString()
                        val ruleItem = item.ruleItem
                        if (null != ruleItem) {
                            when {
                                ruleItem.alarmUpper == ruleItem.alarmDown -> {
                                    holder.setTextColor(
                                        R.id.item_detail_value,
                                        Color.parseColor("#FFFFFF")
                                    )
                                }
                                ruleItem.alarmUpper < ToolsHelper.toDouble(item.value) -> {
                                    holder.setTextColor(
                                        R.id.item_detail_value,
                                        Color.parseColor("#FF4444")
                                    )
                                }
                                ruleItem.alarmDown > ToolsHelper.toDouble(item.value) -> {
                                    holder.setTextColor(
                                        R.id.item_detail_value,
                                        Color.parseColor("#008577")
                                    )
                                }
                                else -> {
                                    holder.setTextColor(
                                        R.id.item_detail_value,
                                        Color.parseColor("#FFFFFF")
                                    )
                                }
                            }
                        }
                    }
                })

            }

        }

    lateinit var photoPath: String
    val REQUEST_IMAGE_CAPTURE = 10013

    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            val c: ComponentName? = takePictureIntent.resolveActivity(packageManager)
            if (null == c) {
                "启动相机失败".showMessage()
            } else {
                val photoURI = FileHelper.getFileUri(
                    File.createTempFile(
                        TimeHelper.getTimeMillis().toString(),
                        ".jpg",
                        File(FileHelper.getImagePath())
                    ).also { photoPath = it.absolutePath }
                )

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
    }
}